package com.example.utils;

import com.deepoove.poi.XWPFTemplate;
import com.example.pojo.dto.AccessDTO;
import com.example.pojo.entity.Contract;
import org.springframework.util.ResourceUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * 合同word文件生成工具类
 *
 * @author ding
 * @since 2024/6/2
 */
public class WordUtils {

    public String createWord(AccessDTO accessDTO) throws IOException {
        File file = ResourceUtils.getFile("classpath:doc/项目合作协议书模版.docx");
        String outPath = ".\\files\\" + accessDTO.getProjectName() +  ".docx";

        Map<String,Object> wdMap = new HashMap<>();

        wdMap.put("JIA",accessDTO.getEntrustName());
        wdMap.put("YI",accessDTO.getTeamName());
        wdMap.put("ProjectName",accessDTO.getProjectName());
        wdMap.put("Investment",accessDTO.getBudget());
        wdMap.put("contractor", accessDTO.getContractor());
        wdMap.put("signedTime", LocalDate.now().toString());

        XWPFTemplate template = XWPFTemplate.compile(file).render(wdMap);

        FileOutputStream fos = new FileOutputStream(new File(outPath));
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        template.write(bos);
        byte[] bytes = bos.toByteArray();
        template.write(fos);

        String filePath = outPath.substring(0,outPath.lastIndexOf(".")) + ".pdf";
        Doc2PdfUtil.doc2pdf(bytes,filePath);
        fos.flush();
        fos.close();
        bos.flush();
        bos.close();
        template.close();

        return filePath;
    }
}
